package com.xieyingwangluo.yxpart.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.UUID;

/**
 * 字符串组建类
 */
public class StringBuildUtils {

    /**
     * 生成UUID
     * @return
     */
    public static String buildUUID(){
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        return uuid;
    }

    /**
     * 字符串格式化
     * @param dt
     * @param format
     * @return
     */
    public static String formatDate(java.util.Date dt, String format){
        if(dt==null){
            return null;
        }

        SimpleDateFormat sdf=new SimpleDateFormat(format);
        return sdf.format(dt);
    }

    public static String serialize(Object obj){
        try {
            //ByteArrayOutputStream 用于存储序列化的Session对象
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            //将Object对象输出成byte数据
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(obj);

            //将字节码，编码成String类型数据
            return Base64.getEncoder().encodeToString(bos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("序列化失败");
        }
    }

    public static Object deserializ(String str) {
        try {
            //读取字节码表
            ByteArrayInputStream bis  = new ByteArrayInputStream(Base64.getDecoder().decode(str));

            //将字节码反序列化成 对象
            ObjectInputStream in = new ObjectInputStream(bis);
            Object obj = in.readObject();
            return obj;
        } catch (Exception e) {
            throw new RuntimeException("反序列化失败");
        }
    }


}
